package net.luoran.dvm.controller;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import net.luoran.dvm.common.annotation.PassToken;
import net.luoran.dvm.common.base.Result;
import net.luoran.dvm.common.util.CiphertextUtil;
import net.luoran.dvm.common.util.JwtUtil;
import net.luoran.dvm.entity.SysUserDO;
import net.luoran.dvm.entity.UserContent;
import net.luoran.dvm.service.SysUserService;
import net.luoran.dvm.service.UserContentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
 * @author ：M1nG
 * @date ：Created in 2020/11/6 10:46
 * @description：
 * @version: 1.0
 */
@Controller
@RequestMapping(value = "/")
@PassToken
public class LoginController {

    @Value("${server.servlet.context-path}")
    public String contextPath;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private UserContentService userContentService;

    @GetMapping("/login")
    public String login(Model model) {
        model.addAttribute("contextPath", contextPath);
        return "login";
    }

    @PostMapping("/user/login")
    @ResponseBody
    public Result userLogin(@RequestParam("loginName") String loginName, @RequestParam("password") String password, Model model) {
        Result<Object> result = Result.ok();
        QueryWrapper<SysUserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("login_name", loginName);
        SysUserDO one = sysUserService.getOne(queryWrapper);
        if (one == null) {
            result = Result.error("账户名不存在！");
        }
        String encode = Base64.decodeStr(password);
        String s = SecureUtil.md5(encode + one.getSalt());
        if (!s.equals(one.getPassword())) {
            result = Result.error("账户名或密码错误！");
        } else {
            UserContent userContent = userContentService.getUserContent(one.getUserId());
            result.setToken(JwtUtil.sign(new CiphertextUtil().encrypt(JSONUtil.parse(userContent).toJSONString(0))));
            result.setData(userContent.getUserName());
        }
        model.addAttribute("contextPath", contextPath);
        return result;
    }


}
